package com.cookie.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.cookie.config.MysqlConfig;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Function;

/**
 * 用于查询mysql中的数据来实现全量同步
 */
public class MysqlUtil {

    public DruidDataSource dataSource = new DruidDataSource();

    public MysqlUtil(MysqlConfig mysqlConf){
        // 数据源的一系列参数
        dataSource.setDriverClassName(mysqlConf.getDriver());
        dataSource.setUrl(mysqlConf.getUrl());
        dataSource.setUsername(mysqlConf.getUsername());
        dataSource.setPassword(mysqlConf.getPassword());
        // 这些参数有空可以看一下
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(mysqlConf.getMaxActive());
        // dataSource.setMaxWait(60000);
        dataSource.setMaxWait(-1);  // 将建立连接等待时间改为无限
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setValidationQuery("select 1");
        try {
            dataSource.init();
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        System.out.println("data source init success");
    }

    public static Object sqlRS(DataSource ds, String sql, Function<ResultSet, Object> fun){
        try(Connection conn = ds.getConnection()){
            try(PreparedStatement pstmt = conn.prepareStatement(sql,
                    ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY)){
                pstmt.setFetchSize(Integer.MIN_VALUE);
                try (ResultSet rs = pstmt.executeQuery()){
                    return fun.apply(rs);
                }
            }
        }catch (Exception e){
            System.out.println("sql rs has error.");
            throw new RuntimeException(e);
        }
    }

}
